﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.loto.Common.DBUtility;
using System.Data.SqlClient;
using com.huigo.Framework.Model;

namespace com.huigo.Framework.BLL
{
    public class PolicyInfoAir
    {
        public static List<Model.PolicyInfoAir> GetPolicyInfoAirList(long orderFid)
        {
            List<string> fields = new List<string>() 
             {
                "POLICY_ID",
                "POLICY_ORDER_FID",
                "POLICY_HOLDER_NAME",
                "POLICY_HOLDER_CREDENTIAL_TYPE",
                "POLICY_HOLDER_CREDENTIAL_NO",
                "POLICY_HOLDER_BIRTH",
                "POLICY_HOLDER_GENDER"
                ,"POLICY_INSURED_NAME"
                ,"POLICY_INSURED_CREDENTIAL_TYPE"
                ,"POLICY_INSURED_CREDENTIAL_NO"
                ,"POLICY_INSURED_BIRTH"
                ,"POLICY_INSURED_GENDER"
                ,"POLICY_FLIGHT_NO"
                ,"POLICY_FROM_PERIOD"
                ,"POLICY_INSURED_TEL"
                ,"POLICY_INSURED_EMAIL",
                "POLICY_STATUS"
                ,"POLICY_NO",
                "HG_POLICY_STATUS.STATUS_DESC",
                "HG_POLICY_FEE_STATUS.STATUS_DESC AS FEE_STATUS_DESC,POLICY_FEE_STATUS,POLICY_UNIT_PRICE,POLICY_COUNT,POLICY_CUST_FID"
             };
            List<JoinStatement> joinList = new List<JoinStatement>()
            {
                new JoinStatement("LEFT","[HG_POLICY_STATUS]","POLICY_STATUS=STATUS_ID"),
                new JoinStatement("LEFT","[HG_POLICY_FEE_STATUS]","POLICY_FEE_STATUS=[HG_POLICY_FEE_STATUS].STATUS_ID")
            };
            List<WhereStatement> whereList = null;
            whereList = new List<WhereStatement>()
                {
                    new WhereStatement("POLICY_ORDER_FID","=",orderFid.ToString(),"")
               };
            List<Model.PolicyInfoAir> PolicyInfoAirList = null;
            PolicyInfoAirList = SqlServerDal.PolicyInfoAir.GetItems(fields, joinList, whereList, null, null);
            return PolicyInfoAirList;

        }

        public static bool UpdatePolicyInfoAir(long OrderID, int PolicyStatus)
        {
            List<WhereStatement> whereList = new List<WhereStatement>()
            {
                    new WhereStatement("POLICY_ORDER_FID","=",OrderID.ToString(),"")
            };

            Model.PolicyInfoAir PolicyInfo = new Model.PolicyInfoAir();
            PolicyInfo.PolicyStatus = PolicyStatus;
            return SqlServerDal.PolicyInfoAir.Update(PolicyInfo, whereList, null);
        }
        public static Model.PolicyInfoAir GetPolicyInfoAirById(long id)
        {
            Model.PolicyInfoAir policy = new Model.PolicyInfoAir();
            policy.PolicyId = id;
            List<string> fields = new List<string>() 
             {
                "POLICY_ID",
                "POLICY_ORDER_FID",
                "POLICY_HOLDER_NAME",
                "POLICY_HOLDER_CREDENTIAL_TYPE",
                "POLICY_HOLDER_CREDENTIAL_NO",
                "POLICY_HOLDER_BIRTH",
                "POLICY_HOLDER_GENDER"
                ,"POLICY_INSURED_NAME"
                ,"POLICY_INSURED_CREDENTIAL_TYPE"
                ,"POLICY_INSURED_CREDENTIAL_NO"
                ,"POLICY_INSURED_BIRTH"
                ,"POLICY_INSURED_GENDER"
                ,"POLICY_FLIGHT_NO"
                ,"POLICY_FROM_PERIOD"
                ,"POLICY_INSURED_TEL"
                ,"POLICY_INSURED_EMAIL",
                "POLICY_STATUS"
                ,"POLICY_NO",
                "STATUS_DESC,POLICY_CUST_FID,POLICY_UNIT_PRICE,POLICY_COUNT,POLICY_FEE_STATUS,POLICY_OUT_ORDER_NO "
             };
            List<JoinStatement> joinList = new List<JoinStatement>()
            {
                new JoinStatement("LEFT","[HG_POLICY_STATUS]","POLICY_STATUS=STATUS_ID"),
                new JoinStatement("INNER","[HG_ORDER_INFO]","ORDER_ID=POLICY_ORDER_FID")
            };
            return SqlServerDal.PolicyInfoAir.GetItem(policy, fields, joinList, null);
        }

        public static List<Model.PolicyInfoAir> PolicyInfoAirIsExisted(long cid)
        {
            List<Model.PolicyInfoAir> PolicyInfoAirInfo = new List<Model.PolicyInfoAir>();
            List<string> fields = new List<string>() 
            {
                "POLICY_ORDER_FID,POLICY_STATUS,POLICY_FEE_STATUS",
            };
            List<WhereStatement> whereList = new List<WhereStatement>()
            {
                new WhereStatement("POLICY_ID","=",cid.ToString()," ")
                //new WhereStatement("POLICY_STATUS","=","'"+policyStatus+"'"," AND"),
               //  new WhereStatement("[HG_POLICY_FEE_STATUS].STATUS_ID","=","'"+feeStatus+"'"," ")
            };
            List<JoinStatement> joinList = new List<JoinStatement>()
            {
                new JoinStatement("LEFT","[HG_POLICY_STATUS]","POLICY_STATUS=STATUS_ID"),
                new JoinStatement("LEFT","[HG_POLICY_FEE_STATUS]","POLICY_FEE_STATUS=[HG_POLICY_FEE_STATUS].STATUS_ID")
            };
            PolicyInfoAirInfo = SqlServerDal.PolicyInfoAir.GetItems(fields, joinList, whereList, null, null);
            return PolicyInfoAirInfo;
        }
        //退款/退款方法
        public static bool UpdatPolicyInfoAirStatus(string PolicyID, long userID, int type)
        {
            string[] arr = PolicyID.Split(',');
            string PolicyIDSendPrice = string.Empty;
            string PolicyIDBackPrice = string.Empty;
            string PolicyIDBackPro = string.Empty;

            string policyTravelID = string.Empty;//旅游险 退款
            string policyBackTravelID = string.Empty;//旅游险 退保
            string policyAirID = string.Empty;//航空意外险 退款
            string policyBackAirID = string.Empty;//航空意外险 退保
            bool result = false;
            long insType = Convert.ToInt64(arr[0]) % 1000;
            switch (insType)
            {
                case (int)Dict.InsType.Travel:
                    foreach (string item in arr)
                    {
                        Model.PolicyInfoTravel travel = BLL.PolicyInfoTravel.PolicyTravelByID(Convert.ToInt64(item));
                        int PolicyTravelFeeStatus = travel.PolicyFeeStatus;
                        int PolicyTravelStatus = travel.PolicyStatus;
                        if (PolicyTravelFeeStatus == (int)Dict.PolicyFeeStatus.Paid && PolicyTravelStatus == (int)Dict.PolicyStatus.InsuredFails)//退款
                        {
                            policyTravelID += item + ",";
                        }
                        else if (PolicyTravelFeeStatus == (int)Dict.PolicyFeeStatus.Paid && PolicyTravelStatus == (int)Dict.PolicyStatus.SurrenderFails)//退款
                        {
                            policyTravelID += item + ",";

                        }
                        else if (PolicyTravelFeeStatus == (int)Dict.PolicyFeeStatus.Paid && PolicyTravelStatus == (int)Dict.PolicyStatus.InsuredSuc)//退保
                        {
                            policyBackTravelID += item + ",";

                        }
                        else
                            break;

                    }
                    break;
                case (int)Dict.InsType.Air:
                    foreach (string item in arr)
                    {
                        Model.PolicyInfoAir PolicyInfoAir = GetPolicyInfoAirById(Convert.ToInt64(item));
                        int PolicyFeeStatus = PolicyInfoAir.PolicyFeeStatus;
                        int PolicyStatus = PolicyInfoAir.PolicyStatus;
                        if (PolicyFeeStatus == (int)Dict.PolicyFeeStatus.Paid && PolicyStatus == (int)Dict.PolicyStatus.InsuredFails)//退款
                        {
                            policyAirID += item + ",";
                        }
                        else if (PolicyFeeStatus == (int)Dict.PolicyFeeStatus.Paid && PolicyStatus == (int)Dict.PolicyStatus.SurrenderFails)//退款
                        {
                            policyAirID += item + ",";

                        }
                        else if (PolicyFeeStatus == (int)Dict.PolicyFeeStatus.Paid && PolicyStatus == (int)Dict.PolicyStatus.InsuredSuc)//退保
                        {
                            policyBackAirID += item + ",";

                        }
                        else
                            break;
                    }
                    break;
                default:
                    break;
            }
            //航空意外险
            string[] policyAirIDs = null;
            string[] policyBackAirIDs = null;
            if (!string.IsNullOrEmpty(policyAirID) && policyAirID.EndsWith(","))
            {
                policyAirID = policyAirID.Substring(0, policyAirID.Length - 1);
                policyAirIDs = policyAirID.Split(',');
                if (arr.Length == policyAirIDs.Length)
                {
                    DOCancelAir(userID, policyAirIDs, policyBackAirIDs, type);
                    result = true;
                }
            }
            if (!string.IsNullOrEmpty(policyBackAirID) && policyBackAirID.EndsWith(","))
            {
                policyBackAirID = policyBackAirID.Substring(0, policyBackAirID.Length - 1);
                policyBackAirIDs = policyBackAirID.Split(',');
                if (arr.Length == policyBackAirIDs.Length)
                {
                    DOCancelAir(userID, policyAirIDs, policyBackAirIDs, type);
                    result = true;
                }
            }

            //旅游险
            string[] policyTravelIDs = null;
            string[] policyBackTravelIDs = null;
            if (!string.IsNullOrEmpty(policyTravelID) && policyTravelID.EndsWith(","))
            {
                policyTravelID = policyTravelID.Substring(0, policyTravelID.Length - 1);
                policyTravelIDs = policyTravelID.Split(',');
                if (arr.Length == policyTravelIDs.Length)
                {
                    DOCancelTravel(policyTravelIDs, userID, policyBackTravelIDs, type);
                    result = true;
                }
            }
            if (!string.IsNullOrEmpty(policyBackTravelID) && policyBackTravelID.EndsWith(","))
            {
                policyBackTravelID = policyBackTravelID.Substring(0, policyBackTravelID.Length - 1);
                policyBackTravelIDs = policyBackTravelID.Split(',');
                if (arr.Length == policyBackTravelIDs.Length)
                {
                    DOCancelTravel(policyTravelIDs, userID, policyBackTravelIDs, type);
                    result = true;
                }
            }
            return result;
        }
        /// <summary>
        /// //航空意外险
        /// </summary>
        /// <param name="insType">保险类型</param>
        /// <param name="userID">操作人</param>
        /// <param name="policyAirIDs">退款保单ID</param>
        /// <param name="policyBackAirIDs">退保保单id</param>
        private static void DOCancelAir(long userID, string[] policyAirIDs, string[] policyBackAirIDs, int type)
        {

            //航空意外险
            if (policyAirIDs != null)
            {
                foreach (var AirID in policyAirIDs)
                {
                    if (type == (int)Dict.UpdatePolicyStatus.SendPolicy)
                    {
                        Model.PolicyInfoAir air = GetPolicyInfoAirById(Convert.ToInt64(AirID));
                        Model.OrderInfo order = BLL.OrderInfo.GetOrderInfoById(air.PolicyOrderFid);

                        Pay.ApprovalPolicy(order.OrderInsTypeFid, order.OrderId, order.OrderNo, order.OrderProductCode);//投保
                    }
                    else
                    {
                        DoCancelFeePolicy(Convert.ToInt64(AirID), userID);//退款
                    }
                }
            }
            if (policyBackAirIDs != null)
            {
                foreach (var AirID in policyBackAirIDs)
                {
                    BLL.Pay.DoCancelPolicy(Convert.ToInt64(AirID), userID);//退保
                }
            }
        }
        /// <summary>
        /// 旅游险
        /// </summary>
        /// <param name="insType">保险类型</param>
        /// <param name="policyTravelIDs">退款保单ID</param>
        /// <param name="userID">操作人</param>
        /// <param name="policyBackTravelIDs">退保保单id</param>
        private static void DOCancelTravel(string[] policyTravelIDs, long userID, string[] policyBackTravelIDs, int type)
        {
            //旅游险
            if (policyTravelIDs != null)
            {
                foreach (var TravelID in policyTravelIDs)
                {
                    if (type == (int)Dict.UpdatePolicyStatus.SendPolicy)//投保
                    {
                        Model.PolicyInfoTravel Travel = BLL.PolicyInfoTravel.PolicyTravelByID(Convert.ToInt64(TravelID));
                        Model.OrderInfo order = BLL.OrderInfo.GetOrderInfoById(Travel.PolicyOrderFid);

                        Pay.ApprovalPolicy(order.OrderInsTypeFid, order.OrderId, order.OrderNo, order.OrderProductCode);//投保
                    }
                    else
                    {
                        DoCancelFeePolicy(Convert.ToInt64(TravelID), userID);//退款
                    }
                }
            }
            if (policyBackTravelIDs != null)
            {
                foreach (var TravelID in policyBackTravelIDs)
                {
                    BLL.Pay.DoCancelPolicy(Convert.ToInt64(TravelID), userID);//退保
                }
            }
        }
        /// <summary>
        /// //退款
        /// </summary>
        /// <param name="insType"></param>
        /// <param name="policyID"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        private static bool DoCancelFeePolicy(long policyID, long userID)
        {
            long insType = policyID % 1000; ;
            switch (insType)
            {
                case (int)Dict.InsType.Travel:
                    Model.PolicyInfoTravel travel = BLL.PolicyInfoTravel.PolicyTravelByID(policyID);
                    string policyOrderNOTravel = travel.PolicyOutOrderNo;//对外订单号
                    long custFIDTravel = travel.PolicyCustFid;//用户id
                    decimal payTravelPrice = travel.PolicyUnitPrice * travel.PolicyCount;//退款价格
                    using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                    {
                        try
                        {
                            //修改保单状态为退保成功或投保失败
                            Model.PolicyInfoTravel policyInfo = new Model.PolicyInfoTravel();
                            policyInfo.PolicyFeeStatus = (int)Dict.PolicyFeeStatus.RefundSuc;
                            List<WhereStatement> travelWhereList = new List<WhereStatement>()
                                {
                                      new WhereStatement("POLICY_ID","=",policyID.ToString(),""),
                                };
                            BLL.CustFeeFlow.InsertFeeFLow(custFIDTravel, userID, policyOrderNOTravel, policyID, payTravelPrice, trans);//插入余额操作流
                            if (BLL.CustInfo.updateFee(custFIDTravel, payTravelPrice, trans) > 0)//更新用户余额
                            {
                                SqlServerDal.PolicyInfoTravel.Update(policyInfo, travelWhereList, trans);//更新保单费用状态
                                trans.Commit();
                                return true;
                            }
                        }
                        catch
                        {
                            trans.Rollback();
                            return false;
                        }

                    }
                    break;
                case (int)Dict.InsType.Air:
                    Model.PolicyInfoAir PolicyInfoAir = BLL.PolicyInfoAir.GetPolicyInfoAirById(policyID);
                    string policyOrderNO = PolicyInfoAir.PolicyOutOrderNo;//对外订单号
                    long custFID = PolicyInfoAir.PolicyCustFid;//用户id
                    decimal payPrice = PolicyInfoAir.PolicyUnitPrice * PolicyInfoAir.PolicyCount;//退款价格
                    {
                        using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                        {
                            try
                            {
                                Model.PolicyInfoAir policyInfo = new Model.PolicyInfoAir();
                                policyInfo.PolicyFeeStatus = (int)Dict.PolicyFeeStatus.RefundSuc;
                                List<WhereStatement> airWhereList = new List<WhereStatement>()
                                {
                                      new WhereStatement("POLICY_ID","=",policyID.ToString(),""),
                                };
                                BLL.CustFeeFlow.InsertFeeFLow(custFID, userID, policyOrderNO, policyID, payPrice, trans);//插入余额操作流
                                if (BLL.CustInfo.updateFee(custFID, payPrice, trans) > 0)//更新用户余额
                                {
                                    SqlServerDal.PolicyInfoAir.Update(policyInfo, airWhereList, trans);//更新保单费用状态
                                    trans.Commit();
                                    return true;
                                }
                            }
                            catch
                            {
                                trans.Rollback();
                                return false;
                            }
                        }
                    }
                    break;

            }
            return false;

        }

        /// <summary>
        /// 添加保险订单
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <param name="holderName">投保人姓名</param>
        /// <param name="holderType">投保人证件类型</param>
        /// <param name="holderNo">投保人证件号</param>
        /// <param name="holderBirth">投保人出生日期</param>
        /// <param name="holderGender">投保人性别</param>
        /// <param name="insuredName">被保人姓名</param>
        /// <param name="insuredType">被保人证件类型</param>
        /// <param name="insuredNo">被保人证件号</param>
        /// <param name="insuredBirth">被保人出生日期</param>
        /// <param name="insuredGender">被保人性别</param>
        /// <param name="fromPeriod">保险起期</param>
        /// <param name="insurdeTel">被抱人手机</param>
        /// <param name="insuredEmail">被保人邮箱</param>
        /// <param name="count">购买份数</param>
        /// <returns></returns>
        public static long InsertPolicyInfoAir(long orderId, long custFid, string holderName, string holderType, string holderNo, string holderBirth, string holderGender, string insuredName, string insuredType, string insuredNo, string insuredBirth, string insuredGender, string fromPeriod, int count, decimal price)
        {
            Model.PolicyInfoAir policyInfoAir = new com.huigo.Framework.Model.PolicyInfoAir();
            policyInfoAir.PolicyOrderFid = orderId;
            policyInfoAir.PolicyHolderName = holderName;
            policyInfoAir.PolicyHolderCredentialType = holderType;
            policyInfoAir.PolicyHolderCredentialNo = holderNo;
            policyInfoAir.PolicyHolderBirth = Convert.ToDateTime(Convert.ToDateTime(holderBirth).ToString("yyyy-MM-dd"));
            policyInfoAir.PolicyHolderGender = holderGender;
            policyInfoAir.PolicyInsuredName = insuredName;
            policyInfoAir.PolicyInsuredCredentialType = insuredType;
            policyInfoAir.PolicyInsuredCredentialNo = insuredNo;
            policyInfoAir.PolicyInsuredBirth = Convert.ToDateTime(Convert.ToDateTime(insuredBirth).ToString("yyyy-MM-dd"));
            policyInfoAir.PolicyInsuredGender = insuredGender;
            policyInfoAir.PolicyFromPeriod = Convert.ToDateTime(Convert.ToDateTime(fromPeriod).ToString("yyyy-MM-dd"));
            policyInfoAir.PolicyStatus = 1;
            policyInfoAir.PolicyCustFid = custFid;
            policyInfoAir.PolicyCount = count;
            policyInfoAir.PolicyUnitPrice = price;
            policyInfoAir.PolicyInsuredTel = " ";
            return SqlServerDal.PolicyInfoAir.AddPolicy(policyInfoAir, null);
        }

        public static long InsertPolicyInfoAir(Model.PolicyInfoAir policyInfoAir, SqlTransaction trans)
        {
            return SqlServerDal.PolicyInfoAir.AddPolicy(policyInfoAir, trans);
        }
        //航意险
        public static List<Model.PolicyInfoAir> GetInvoiceOrderPolicyAirCustName(long custFID,int insType, long orderID, int pageSize, int pageIndex,DateTime orderStart, DateTime orderEnd)
        {
            List<string> fields = new List<string>() 
             {
                @"POLICY_INSURED_NAME"
                ,"POLICY_INSURED_CREDENTIAL_TYPE"
                ,"POLICY_INSURED_CREDENTIAL_NO"
                ,"POLICY_INSURED_BIRTH"
                ,"POLICY_INSURED_GENDER"
                ,"POLICY_FLIGHT_NO"
                ,"POLICY_FROM_PERIOD"
                ,"POLICY_INSURED_TEL"
                ,"POLICY_INSURED_EMAIL,POLICY_NO,ORDER_NO"
             };
            List<JoinStatement> joinList = new List<JoinStatement>()
            {
                new JoinStatement("LEFT","[HG_ORDER_INFO]","ORDER_ID=POLICY_ORDER_FID")
            };
            List<WhereStatement> whereList = null;
            whereList = new List<WhereStatement>();
            if (orderStart != DateTime.MinValue && orderEnd != DateTime.MinValue)
            {
                whereList.Add(new WhereStatement("ORDER_CREATED_ON", "BETWEEN", "'" + orderStart + "' AND '" + orderEnd + "'", "AND"));
            }
            whereList.Add(new WhereStatement("ORDER_INS_TYPE_FID", "=", insType.ToString(), " and"));
            whereList.Add(new WhereStatement("ORDER_CUST_FID", "=", custFID.ToString(), " and"));
            whereList.Add(new WhereStatement("POLICY_CUST_FID", "=", custFID.ToString(), " and")); 
            whereList.Add(new WhereStatement("POLICY_STATUS", "=", ((int)Dict.PolicyStatus.InsuredSuc).ToString(), "  "));
           // whereList.Add(new WhereStatement("ORDER_CREATED_ON", ">=", "dateadd(mm,-1,getdate())", "  "));
            List<OrderByStatement> order = new List<OrderByStatement>();
            order.Add(new OrderByStatement("ORDER_CREATED_ON", false));
            List<Model.PolicyInfoAir> PolicyInfoAir = null;
            int recordCount = 0;
            int pageCount = 0;
            PolicyInfoAir = SqlServerDal.PolicyInfoAir.GetItemsByProc(fields, joinList, whereList, order, "[PROC_PAGINATION_OUT]", pageSize, pageIndex, out recordCount, out pageCount, null);
            PolicyInfoAir.ForEach(delegate(Model.PolicyInfoAir info)
            {
                info.RecordCount = recordCount;
                info.PageCount = pageCount;
            });
            return PolicyInfoAir;
        }
            

    }
}
